# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '20000036': {
        'API_KEY': 'IR7BCLYTZKKOVPAXILGP8YWHL3JVUODU4EDUHSLBHXGV4UWQQKMAKRP8ZOZHUJQIH'
                   'STQ2RMJ8G2UI9AQRBUXQWSSLH0SWRZOUTWL2GVPXITBPCG2ZDJ2MF9CH7L912YA',
    },
    'gateway': 'http://api.wjm886.com/api/pay/create_order',
    'query_gateway': 'http://api.wjm886.com/api/pay/query_order',
}


def _get_pay_type(service):
    if service == 'alipay':  # 支付宝扫码 3.5%
        return '8006'
    elif service == 'unionpay':  # 云闪付扫码 2%
        return '8019'
    elif service == 'alipay_h5':  # 支付宝H5支付 4%
        return '8007'
    elif service == 'quick':  # 快捷支付2%
        return '8001'
    elif service == 'wechat':  # 微信扫码支付3.5%
        return '8002'
    return '8019'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_query_gateway():
    return APP_CONF['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest().upper()
    return sign


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def generate_verify_sign(parameter, key):
    s = ''
    for k, v in sorted(parameter.items()):
        if v == '':
            continue
        s += '%s=%s&' % (k, v)
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("huishengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise SignError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    pay_type = _get_pay_type(service)

    parameter_dict = OrderedDict((
        ('mchId', app_id),  # 商户ID
        ('appId', 'eed6a4bf134e4704a6f867d2865e4c5a'),  # 应用ID,后台创建获取
        ('productId', pay_type),  # 支付产品ID
        ('mchOrderNo', str(pay.id)),  # 商户订单号
        ('currency', 'cny'),  # 币种
        ('amount', str(int(pay_amount * 100))),  # 支付金额
        ('clientIp', _get_device_ip(info)),  # 客户端IP
        ('device', ''),  # 设备
        ('returnUrl', '{}/pay/api/{}/huishengpay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('notifyUrl', '{}/pay/api/{}/huishengpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('subject', 'none'),  # 商品主题
        ('body', 'none'),  # 商品描述信息
        ('param1', ''),  # 扩展参数1
        ('param2', ''),  # 扩展参数2
        ('extra', 'none'),  # 附加参数
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)

    _LOGGER.info("huishengpay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['mchOrderNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("huishengpay response: %s", response.text)
    resp_obj = json.loads(response.text)

    if resp_obj['retCode'] != 'SUCCESS':
        return {'charge_info': resp_obj['retMsg']}
    response_param = dict(resp_obj['payParams'])

    if response_param['payMethod'] == 'codeImg':
        url = response_param['codeUrl']
    else:
        html = response_param['payUrl']
        cache_id = redis_cache.save_html(pay.id, html)
        url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('huishengpay to pay url: %s', url)
    return {'charge_info': url}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("huishengpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("huishengpay notify data: %s, order_id is: %s", data, data['mchOrderNo'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['mchOrderNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("huishengpay notify fatal error, pay object not exists, data: %s" % data)
        raise NotResponsePayIdError('event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise NotPayOrderError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ProcessedPayOrderError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['mchOrderNo']
    # 单位分转换为元
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0-订单生成, 1-支付中, 2-支付成功, 3-业务处理完成
    if trade_status == '2':
        _LOGGER.info('huishengpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    pay = get_pay(pay_id)
    parameter_dict = OrderedDict((
        ('mchId', app_id),  # 商户ID
        ('appId', 'eed6a4bf134e4704a6f867d2865e4c5a'),  # 应用ID,后台创建获取
        ('payOrderId', ''),  # 支付订单号
        ('mchOrderNo', str(pay.id)),  # 商户订单号
        ('executeNotify', False),  # 是否执行回调
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info('huishengpay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['mchOrderNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(), data=parameter_dict, headers=headers, timeout=5)
    data = json.loads(response.text)
    _LOGGER.info('huishengpay query rsp, %s', data)

    if data['retCode'] == 'SUCCESS':
        trade_status = str(data['status'])
        total_fee = float(data.get('amount')) / 100.0
        trade_no = str(data['mchOrderNo'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        check_channel_order(pay_id, total_fee, app_id)
        # 0-订单生成, 1-支付中, 2-支付成功, 3-业务处理完成
        if trade_status == '2':
            _LOGGER.info('huishengpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info(
                'huishengpay query order success,but not pay success or has been processed, status:%s' % trade_status)
    else:
        _LOGGER.warn('huishengpay query data error, error message: %s', data['retMsg'])
